/*
 * $Id: UserEdit.java 17 2014-08-28 10:52:50Z ratking $
 *
 * Copyleft (C) 2014 RatKing. All wrongs reserved.
 */
package cn.ratking.demo.jaws7.system.view;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

import org.omnifaces.util.Messages;
import org.slf4j.Logger;

import cn.ratking.demo.jaws7.model.LogEvent;
import cn.ratking.demo.jaws7.model.User;
import cn.ratking.demo.jaws7.system.service.UserService;

/**
 * 用户查询
 */
@Named
@ConversationScoped
public class UserEdit implements Serializable {

    /** 系统日志 */
    @Inject
    private transient Logger log;
    @Inject
    private UserService userService;
    @Inject
    private Conversation conversation;
    /** 事件源 */
    @Inject
    private Event<LogEvent> logEventSrc;
    /** 用户ID */
    private Long userId;
    /** 选择的用户 */
    private User user;

    @PostConstruct
    public void init() {
        log.debug("Debug: UserEdit.init(), this=" + this);
    }

    @PreDestroy
    public void destroy() {
        log.debug("Debug: UserEdit.destroy(), this=" + this);
    }

    /**
     * 开始业务会话
     */
    public void beginConversation() {
        if (conversation.isTransient()) {
            conversation.begin();
        }
        conversation.setTimeout(300000); //5 * 60 * 1000 (5 minutes)
    }

    /**
     * 结束业务会话
     */
    public void endConversation() {
        if (!conversation.isTransient()) {
            conversation.end();
        }
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public boolean isManaged() {
        return userId != null;
    }

    public User getUser() {
        if (user == null) {
            if (isManaged()) {
                user = userService.findById(userId);
            } else {
                user = new User();
                user.setEnabled(true);
                //user.setVersion(0);
            }
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    /**
     * 添加/修改用户
     *
     * @return 导航页面
     */
    public String save() {
        try {
            if (isManaged()) {
                userService.update(user);
            } else {
                userService.create(user);
            }
            // 结束业务会话
            endConversation();

            String msg = (isManaged() ? "修改" : "添加") + "用户["
                    + user.getUsername() + "]成功";
            log.debug(msg);
            logEventSrc.fire(new LogEvent(LogEvent.LOGTYPE_SECURITY, LogEvent.LOGLEVEL_INFO, msg));
            Messages.addGlobalInfo(msg);
        } catch (Exception ex) {
            String errorMsg = (isManaged() ? "修改" : "添加") + "用户["
                    + user.getUsername() + "]异常：" + ex.getMessage();
            log.error(errorMsg, ex);
            logEventSrc.fire(new LogEvent(LogEvent.LOGTYPE_SECURITY, LogEvent.LOGLEVEL_ERROR, errorMsg));
            Messages.addGlobalError(errorMsg);
            return null;
        }
        return "userQuery?faces-redirect=true";
    }

    /**
     * 返回用户查询列表
     *
     * @return 导航页面
     */
    public String cancel() {
        if (isManaged()) {
            userService.detach(user);
        }
        // 结束业务会话
        endConversation();
        return "userQuery?faces-redirect=true";
    }
}
